package com.example.finalproject;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link Mainpage#newInstance} factory method to
 * create an instance of this fragment.
 */
public class Mainpage extends Fragment implements AdapterView.OnItemClickListener{
    private static final String TAG = "why";
    ArrayList<Database> disheslist;
    MyAdapter myAdapter;
    private ListView lv;
    private ViewPager viewPager3;
    private int imageIds[];
    private String[] titles;
    private ArrayList<ImageView> images;
    private ArrayList<View> dots;
    private TextView title;
    private MyViewPager viewPagerAdapterThree;

    Intent intent;
    private int oldPosition = 0;//记录上一次点的位置
    private int currentItem; //当前页面

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    public Mainpage() {
        // Required empty public constructor
    }
    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment mainpage.
     */
    // TODO: Rename and change types and number of parameters
    public static Mainpage newInstance(String param1, String param2) {
        Mainpage fragment = new Mainpage();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_mainpage, container, false);
        disheslist = new ArrayList<Database>();
        lv = view.findViewById(R.id.mylist);
        MyDBOpenHelper helper = new MyDBOpenHelper();
        SQLiteDatabase db = helper.openDatabase(getContext());
        Cursor cursor = db.rawQuery("select * from dishes1",null);

         while(cursor.moveToNext()){
             int index0 = cursor.getColumnIndex("name");
             int index1 = cursor.getColumnIndex("material");
             int index2 = cursor.getColumnIndex("steps");
             String name = cursor.getString(index0);
             String material = cursor.getString(index1);
             String step = cursor.getString(index2);
             Database list = new Database(name,material,step);
             disheslist.add(list);
             Log.i(TAG, "dishesList: "+disheslist);
         }
            myAdapter = new MyAdapter(getActivity(),R.layout.list_item,disheslist);
            lv.setAdapter(myAdapter);

         lv.setOnItemClickListener(this);


        //图片ID
        imageIds = new int[]{
                R.drawable.mainpage3,
                R.drawable.mainpage2,
                R.drawable.mainpage1
        };
        //图片标题
        titles = new String[]{
                "巨香港式煲仔饭",
                "一起来做滑嫩牛肉饭",
                "超下饭红烧肉！"
        };
        //显示的图片
        images = new ArrayList<ImageView>();
        for (int i = 0; i < imageIds.length; i++) {
            ImageView imageView = new ImageView(getActivity());
            imageView.setBackgroundResource(imageIds[i]);
            images.add(imageView);
        }
        dots = new ArrayList<View>();
        dots.add(view.findViewById(R.id.dot_0));
        dots.add(view.findViewById(R.id.dot_1));
        dots.add(view.findViewById(R.id.dot_2));
        title = view.findViewById(R.id.title);
        title.setText(titles[0]);
        viewPager3 = view.findViewById(R.id.view_pager3);

        viewPagerAdapterThree = new MyViewPager(images);

        viewPager3.setAdapter(viewPagerAdapterThree);

        viewPager3.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                int currentPosition = position % (images.size());
                title.setText(titles[currentPosition]);
                dots.get(oldPosition).setBackgroundResource(R.drawable.dot1);
                dots.get(currentPosition).setBackgroundResource(R.drawable.dot2);
                oldPosition = currentPosition;
                currentItem = currentPosition;
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        handler.sendEmptyMessage(1);
        setFirstLocation();
        return view;

    }

    @Override
    public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
        inflater.inflate(R.menu.my_menu,menu);
        MenuItem item = menu.findItem(R.id.action_search);
        SearchView searchView = (SearchView) item.getActionView();
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                myAdapter.getFilter().filter(newText);
                return false;
            }
        });
        super.onCreateOptionsMenu(menu, inflater);
    }

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            //设置当前页面
            currentItem = viewPager3.getCurrentItem();
            viewPager3.setCurrentItem(currentItem + 1);
            handler.sendEmptyMessageDelayed(1, 2000);
        }
    };
    @Override
    public void onStop() {
        super.onStop();
    }


    private void setFirstLocation() {
        int m = (Integer.MAX_VALUE / 2) % images.size();
        int currentPosition = Integer.MAX_VALUE / 2 - m - 1;
        viewPager3.setCurrentItem(currentPosition);
    }


    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
        Database list1 = disheslist.get(position);
        String name = list1.getName();
        String material = list1.getMaterial();
        String step = list1.getStep();
        intent = new Intent(getActivity(),Details.class);
        intent.putExtra("name_key",name);
        intent.putExtra("material_key",material);
        intent.putExtra("step_key",step);
        startActivity(intent);
    }
}
